<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 12/8/18
 * Time: 5:24 PM
 */

require_once __DIR__.'/vendor/autoload.php';
use Workerman\Connection\AsyncTcpConnection;
use Workerman\Worker;

$worker = new Worker();
/*$command2 = isset($argv[2]) ? $argv[2] : '';
$command3 = isset($argv[3]) ? $argv[3] : '';
$exchange = ($command2 && $command2 !== '-d') ? $command2 : $command3;
if (!$exchange) $exchange = 'binance';*/
$exchange = 'huobi';

$worker->onWorkerStart = function() use ($exchange) {
    // 以websocket协议连接远程websocket服务器
    $con2 = new AsyncTcpConnection('ws://127.0.0.1:7777');
    $con = new AsyncTcpConnection("ws://ws.coincap.io:443/trades/".$exchange);
    $con->transport = 'ssl';
    // 注册连接上后的事件
    $con2->onConnect = function($con){
        echo "connected\n";
    };
    $con->onConnect = function($con){
        echo "connected\n";
    };
    // 远程websocket服务器发来消息时
    $con2->onMessage = function($con, $data){
        //echo "recv: $data\n";
    };
    $lastTimestamp = millisecond();
    $list = [];
    $con->onMessage = function($con, $data) use ($con2, $exchange, &$lastTimestamp, &$list) {
        //if (millisecond() - $lastTimestamp < 500) return false;
        //echo "recv: $data\n";
        $data = json_decode($data, true);
        if (!empty($data)) {
            if (millisecond() <= $lastTimestamp + 1499) {
                $list[] = $data;
            } else {
                $message = json_encode([
                    'flag' => 'r',
                    'event' => 'broadcast',
                    'topic' => 'exchange',
                    'name' => $exchange,
                    'data' => $list
                ]);
                $con2->send($message);
                $lastTimestamp = millisecond();
                $list = [];
            }
        }
    };
    // 连接上发生错误时，一般是连接远程websocket服务器失败错误
    $con->onError = function($con, $code, $msg){
        echo "error: $msg\n";
    };
    // 当连接远程websocket服务器的连接断开时
    $con->onClose = function($con){
        echo "connection closed\n";
        $con->reconnect(1);
    };
    // 设置好以上各种回调后，执行连接操作
    $con2->connect();
    $con->connect();
};

function millisecond() {
    list($msec, $sec) = explode(' ', microtime());
    // return (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return round((floatval($msec) + floatval($sec)) * 1000);
}

Worker::runAll();